package com.mbigger.admin.controller;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.google.common.collect.Maps;
import com.mbigger.admin.beans.PageQuery;
import com.mbigger.admin.beans.PageResult;
import com.mbigger.admin.entity.User;
import com.mbigger.admin.param.UserParam;
import com.mbigger.admin.service.RoleService;
import com.mbigger.admin.service.TreeService;
import com.mbigger.admin.service.UserService;

@RestController
@RequestMapping("/sys/user")
public class UserController {

	@Autowired
	private UserService userService;
	
	@Autowired
	private TreeService treeService;
	
	@Autowired
	private RoleService roleService;
	
	@PostMapping("/save")
	public void save(UserParam param) {
		userService.save(param);
	}

	@PostMapping("/update")
	public void update(UserParam param) {
		userService.update(param);
	}

	@GetMapping("/page")
	public PageResult<User> page(int deptId, PageQuery page) {
		return userService.getPageByDeptId(deptId, page);
	}
	
	@PostMapping("/verify")
	public void verify(HttpServletRequest request, String username, String password) {
		User user = userService.findByKeyword(username);
        String errorMsg = "";

        if (StringUtils.isBlank(username)) {
            errorMsg = "用户名不可以为空";
        } else if (StringUtils.isBlank(password)) {
            errorMsg = "密码不可以为空";
        } else if (user == null) {
            errorMsg = "查询不到指定的用户";
        } else if (!user.getPassword().equals(password)) {
            errorMsg = "用户名或密码错误";
        } else if (user.getStatus() != 1) {
            errorMsg = "用户已被冻结，请联系管理员";
        } else {
            request.getSession().setAttribute("user", user);
            return;
        }
        throw new RuntimeException(errorMsg);
	}
	
    @RequestMapping("/acls")
    public Map<String, Object> acls(@RequestParam("userId") int userId) {
        Map<String, Object> map = Maps.newHashMap();
        map.put("acls", treeService.userAclTree(userId));
        map.put("roles", roleService.getRoleListByUserId(userId));
        return map;
    }
}
